// pages/village/village.js
const app = getApp();
import { getStorage } from "../../../utils/localStorage";
import { baseUrl } from "../../../api/request";
import {
  infoVillage,
  listRuralAttractions,
  listVillageDynamics,
  dynamiGive_option
} from "../../../api/homePage"
import { getMapDistance, getAddress } from "../../../utils/address"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //自定义组件参数
    navData: {
      level: 12,
      title: ''
    },
    // 根据滚动数控制导航栏显隐透明度
    scrollTop: 0,
    //图片地址
    imgUrl: undefined,
    //当前位置经纬度
    latLng: undefined,
    //自定义导航栏高度
    pageTop: app.globalData.navHeight + app.globalData.navTop,
    //轮播图组件参数
    swiper: {
      autoplay: true, //自动切换
      dots: false, //指示点
      dotsColor: "#ffffff", //指示点颜色
      dotsActiveColor: "#4646A0", //选中指示点颜色
      circular: true, //衔接滑动
      duration: 5000, //滑动动画时长
      boxFlag: false,
    },
    //动态列表查询参数
    listQuery: {
      userId: null,
      pageSize: 10,
      pageNum: 1,
      villageId: ""
    },
    //总条数
    total: 0,
    //上拉刷新状态
    showPull: true,
    //详情数据
    info: undefined,
    //景点列表
    attractionsList: [],
    // 用户动态列表左边显示数据
    leftList: [],
    //用户动态列表右边显示数据
    rightList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      imgUrl: baseUrl,
      latLng: getStorage("latLng"),
      "listQuery.userId": getStorage("user").id,
      "listQuery.villageId": options.id
    });
    this.getInfo(options.id);
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //动态点赞静态处理
    let dynamicId = app.globalData.dynamicId,
      dynamicGive = app.globalData.dynamicGive,
      dynamicGiveNum = app.globalData.dynamicGiveNum;
    if (dynamicId) {
      let indexFlag = this.data.leftList.findIndex(item => {
        return item.id === dynamicId
      }),
        index = null,
        value = null,
        num = null;
      if (indexFlag === -1) {
        index = this.data.rightList.findIndex(item => {
          return item.id === dynamicId
        });
        value = "rightList[" + index + "].likeState";
        num = "rightList[" + index + "].likeNumber";
      } else {
        index = this.data.leftList.findIndex(item => {
          return item.id === dynamicId
        });
        value = "leftList[" + index + "].likeState";
        num = "leftList[" + index + "].likeNumber";
      };
      this.setData({
        [value]: dynamicGive === 1 ? true : false,
        [num]: dynamicGiveNum,
      });
    };
  },

  //获取详情数据
  getInfo(id) {
    const _this = this.data;
    infoVillage({
      villageId: id,
      longitude: _this.latLng.lng,
      latitude: _this.latLng.lat
    }).then(res => {
      res.data.data.villageImage = res.data.data.villageImage ? res.data.data.villageImage.split(",") : [];
      res.data.data.imageScale = res.data.data.villageImage;
      this.setData({
        info: res.data.data
      });
      this.getAttractionsList(id);
    });
  },

  //获取景点列表
  getAttractionsList(id) {
    const _this = this.data;
    listRuralAttractions({
      villageId: id,
      longitude: _this.latLng.lng,
      latitude: _this.latLng.lat
    }).then(res => {
      let arr = res.data.data.map(item => ({
        ...item,
        imageScale: item.imageScale ? item.imageScale.split(",") : []
      }));
      this.setData({
        attractionsList: arr
      });
      this.getTrendsList();
    });
  },

  //获取动态列表
  getTrendsList() {
    const _this = this.data;
    let leftArr = [],
      rightArr = [];
    listVillageDynamics(_this.listQuery).then(res => {
      if (!res.data.data.list || res.data.data.list.length === 0) {
        this.setData({
          leftList: [],
          rightList: [],
        })
      } else {
        res.data.data.list.forEach((item, index) => {
          item.imageScale = item.imageScale.split(",");
          item.distance = getMapDistance(_this.latLng.lat, _this.latLng.lng, item.latitude, item.longitude);
          if (index % 2 === 0) {
            leftArr.push(item);
          } else {
            rightArr.push(item);
          };
        });
        this.setData({
          leftList: [..._this.leftList, ...leftArr],
          rightList: [..._this.rightList, ...rightArr],
          total: Math.ceil(res.data.data.total / _this.listQuery.pageSize)
        });
      };
    });
  },

  //乡村景点列表点击事件
  xcListTap(e) {
    const item = e.currentTarget.dataset.item;
    console.log(item, 'item');
    wx.navigateTo({
      url: '/pagesShouYe/pages/jingquDetail/index?id=' + item.landscapesId,
    });
  },

  //用户动态点赞或取消点赞事件
  commentClick(e) {
    let that = this.data,
      item = e.currentTarget.dataset.item,
      index = e.currentTarget.dataset.index,
      title = e.currentTarget.dataset.title,
      flag = !item.likeState ? true : false;
    dynamiGive_option({
      userId: that.listQuery.userId,
      dynamicsId: item.id,
      state: flag
    }).then(res => {
      let state = "";
      let num = "";
      if (res.data.code === 200) {
        if (title === "leftList") {
          state = "leftList[" + index + "].likeState";
          num = "leftList[" + index + "].likeNumber";
        } else if (title === "rightList") {
          state = "rightList[" + index + "].likeState";
          num = "rightList[" + index + "].likeNumber";
        };
        this.setData({
          [state]: flag,
          [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
        });
      };
    });
  },
  //用户动态列表点击事件
  listTap(e) {
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pagesShouYe/pages/listDetail/index?id=' + item.id + '&dynamicType=乡镇动态',
    });
  },

  //地图导航按钮点击事件
  mapDhTap(e) {
    const _this = this.data;
    wx.openLocation({
      name: _this.info.villageName,
      latitude: Number(_this.info.latitude),
      longitude: Number(_this.info.longitude),
    });
  },

  // 监听页面滚动
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
    // 修改状态栏颜色
    if (e.scrollTop < 60) {
      this.setData({
        navData: {
          level: 12,
          title: ''
        },
      });
    } else {
      this.setData({
        navData: {
          level: 2,
          title: '乡村详情'
        },
      });
    };
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let that = this.data;
    if ((that.listQuery.pageNum + 1) <= that.total) {
      this.setData({
        showPull: false,
        "listQuery.pageNum": that.listQuery.pageNum += 1
      });
      this.getTrendsList();
    } else {
      this.setData({
        showPull: true
      });
    };
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})